import { initShaders } from '@/lib/webgl'
export default function (el, vertexDatas, vertexCount, angle) {
    const styles = window.getComputedStyle(el, null)
    el.width = parseInt(styles.width)
    el.height = parseInt(styles.height)
    const gl = el.getContext('webgl2')

    // 顶点着色器
    const VSHADER_SOURCE = `
        attribute vec4 a_Position;
        uniform float u_CosB, u_SinB;
        void main() {
            gl_Position.x = a_Position.x * u_CosB - a_Position.y * u_SinB;
            gl_Position.y = a_Position.x * u_SinB + a_Position.y * u_CosB;
            gl_Position.z = a_Position.z;
            gl_Position.w = 1.0;
            gl_PointSize = 10.0;
        }
    `
    const FSHADER_SOURCE = `
        void main() {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
        }
    `
    if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
        console.log('init shader error')
        return
    }
    const initVertexBuffers = (gl) => {
        const radian = Math.PI * angle / 180.0
        const cosB = Math.cos(radian)
        const sinB = Math.sin(radian)
        console.log(angle, cosB, sinB)
        const uCosB = gl.getUniformLocation(gl.program, 'u_CosB')
        gl.uniform1f(uCosB, cosB)
        const uSinB = gl.getUniformLocation(gl.program, 'u_SinB')
        gl.uniform1f(uSinB, sinB)
        const vertices = new Float32Array(vertexDatas)
        const n = vertexCount
        // 创建缓冲区
        const buffer = gl.createBuffer()
        if (!buffer) {
            return -1
        }
        // 将缓冲区对象绑定到目标
        gl.bindBuffer(gl.ARRAY_BUFFER, buffer)
        // 向缓冲区对象中写入数据
        gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)
        const aPosition = gl.getAttribLocation(gl.program, 'a_Position')
        // 将缓冲区对象分配给attribute变量
        gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0)
        // 连接a_Position变量与分配给它的缓冲区对象
        gl.enableVertexAttribArray(aPosition)
        return n
    }
    // 设置顶点位置
    const n = initVertexBuffers(gl)
    if (n < 0) {
        console.log('initVertexBuffers failed')
        return
    }
    gl.clearColor(0.0, 0.0, 0.0, 1.0)
    gl.clear(gl.COLOR_BUFFER_BIT)
    gl.drawArrays(gl.TRIANGLES, 0, n)
}